<template>
  <el-dialog
    :title="action.type === 1 ? '新增站点' : '编辑站点'"
    :visible.sync="action.show"
    width="1000px"
    center
    top="30px"
    @close="resetActionForm"
  >
    <el-dialog
      width="800px"
      title="选择位置"
      :visible.sync="mapInfo.show"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <template v-if="mapInfo.show">
        <el-amap
          class="amap-box"
          :zoom="mapInfo.zoom"
          :center="mapInfo.center"
          :events="events"
          :mapStyle="mapInfo.mapStyle"
          style="height: 300px"
        >
          <el-amap-marker
            vid="marker"
            :position="mapInfo.center"
          ></el-amap-marker>
        </el-amap>
      </template>
      <p>
        标记点：{{ mapInfo.address }}，经度：{{ mapInfo.lng }}，纬度：{{
          mapInfo.lat
        }}
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapInfo.show = false">取 消</el-button>
        <el-button type="primary" @click="submitAddress">确 定</el-button>
      </span>
    </el-dialog>
    <div class="dialog-content">
      <el-form
        :model="actionForm"
        :rules="rules"
        ref="actionForm"
        label-width="100px"
        class="demo-actionForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站点名称" prop="station_Name">
              <el-input v-model="actionForm.station_Name">
                <template slot="append">自助洗车站</template>
              </el-input>
              <p class="ts">提示：名称不能重复，输入2-10个字！</p>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属商户号" prop="merchant_num">
              <el-input v-model="actionForm.merchant_num"> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="所属关系">
          <div v-for="(i, index) in baseRegionTable" :key="index">
            {{ i.merchant_TypeName }}：{{ i.store_Name }}
          </div>
        </el-form-item>
        <el-form-item label="站点类型">
          <template v-if="baseRegionTable.length">
            {{
              baseRegionTable[0].merchant_Type == 10
                ? "普通站点类型"
                : "合伙站点类型"
            }}
          </template>
        </el-form-item>
        <el-form-item label="站点地址" prop="cityVal">
          <selectCity ref="selectCity" :cityVal.sync="actionForm.cityVal" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            style="width: 400px"
            v-model="actionForm.address"
            placeholder="如道路、门牌号、小区、楼栋号、单元室等"
          >
          </el-input>
        </el-form-item>
        <div class="site-address">
          <el-input
            disabled
            style="width: 250px"
            v-model="actionForm.lon"
            placeholder=""
          >
            <template slot="prepend">经度：</template>
          </el-input>
          <el-input
            disabled
            style="width: 250px; marginLeft: 10px;"
            v-model="actionForm.lat"
            placeholder=""
          >
            <template slot="prepend">纬度：</template>
          </el-input>
          <el-button style="marginLeft: 10px;" @click="getLatLon"
            >获取经纬度</el-button
          >
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="所在场景" prop="scenario">
              <el-select
                v-model="actionForm.scenario"
                placeholder="请选择活动区域"
              >
                <el-option label="小区" value="小区"></el-option>
                <el-option label="商场" value="商场"></el-option>
                <el-option label="露天" value="露天"></el-option>
                <el-option label="加油站" value="加油站"></el-option>
                <el-option label="办公场所" value="办公场所"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="站点运维"
              prop="operations"
              v-if="
                baseRegionTable.length && baseRegionTable[0].merchant_Type != 10
              "
            >
              <el-select
                v-model="actionForm.operations"
                placeholder="请选择活动区域"
              >
                <el-option label="无托管" value="0"></el-option>
                <el-option label="全托" value="1"></el-option>
                <el-option label="托管加水/加泡沫" value="2"></el-option>
                <el-option label="托管清洁" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="停车收费" prop="park">
              <el-select v-model="actionForm.park" placeholder="请选择活动区域">
                <el-option label="无停车收费" value="无停车收费"></el-option>
                <el-option
                  label="收取外来车辆停车费"
                  value="收取外来车辆停车费"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="营业时间" prop="date">
          <el-time-picker
            is-range
            value-format="HH:mm"
            v-model="actionForm.date"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            @blur="changeDate"
          >
          </el-time-picker>
          <el-switch
            style="marginLeft: 10px"
            v-model="actionForm.isDateAll"
            active-text="24h"
            inactive-text="自定义"
          >
          </el-switch>
          <p class="ts">提示：营业时间，控制能不能下单，提示店铺是否打烊</p>
        </el-form-item>
        <div class="btn-wrap">
          <el-button type="primary" @click="submitActionForm">提交</el-button>
          <!-- v-if="action.type === 1" -->
          <el-button @click="resetActionForm">重置</el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>
<script>
import selectCity from "@/components/selectCity";
import uploadImg from "@/components/uploadImg";

export default {
  data() {
    let _this = this;
    return {
      // 操作
      action: {
        // 1添加 2修改
        type: 1,
        // 是否显示操作弹窗
        show: false
      },
      // 所属关系
      baseRegionTable: [],
      events: {
        init: map => {
          let geocoder = new AMap.Geocoder({
            city: "全国"
          });
          geocoder.getLocation(_this.mapInfo.address, (status, result) => {
            if (status === "complete" && result.geocodes.length) {
              let lnglat = result.geocodes[0].location;
              _this.mapInfo.lng = lnglat.lng;
              _this.mapInfo.lat = lnglat.lat;
              _this.mapInfo.center = [lnglat.lng, lnglat.lat];
            }
          });
        },
        click: e => {
          let { lng, lat } = e.lnglat;
          this.mapInfo.center = [lng, lat];
          this.mapInfo.lng = lng;
          this.mapInfo.lat = lat;
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                _this.mapInfo.address = result.regeocode.formattedAddress;
              }
            }
          });
        }
      },
      mapInfo: {
        center: [0, 0], //地图中心点坐标 济南市
        mapStyle: "amap://styles/8b6be8ec497009e17a708205348b899a", //设置地图样式
        zoom: 12, //初始化地图显示层级
        address: "", // 初始化地图地址
        lng: 0,
        lat: 0,
        show: false
      },
      actionForm: {
        address: "",
        station_Name: "",
        merchant_num: "",
        cityVal: [],
        lon: "",
        lat: "",
        scenario: "",
        operations: "",
        park: "",
        isDateAll: false,
        date: null
      },
      rules: {
        station_Name: [
          { required: true, message: "请输入站点名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字", trigger: "blur" },
          { validator: this.validateStationName, trigger: "blur" }
        ],
        merchant_num: [
          { required: true, message: "请输入所属商户号", trigger: "blur" },
          {
            validator: this.getAccountStoreMerchantRelationList,
            trigger: "blur"
          }
        ],
        cityVal: [
          { required: true, message: "请选择站点地址", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        scenario: [
          { required: true, message: "请选择所在场景", trigger: "blur" }
        ],

        operations: [
          { required: true, message: "请选择站点运维", trigger: "blur" }
        ],
        park: [{ required: true, message: "请选择停车收费", trigger: "blur" }]
      }
    };
  },
  methods: {
    // 修改时间
    changeDate(e) {
      if (e.value && e.value.length) {
        this.actionForm.isDateAll = false;
      }
    },
    // 新增请求
    async add() {
      const res = await this.$api.carWashStation.ADDSelfServiceCarWashStationList(
        {
          station_Name: this.actionForm.station_Name,
          merchant_Num: this.actionForm.merchant_num,
          address: this.actionForm.address,
          base_Region_Id: this.actionForm.cityVal[2],
          base_Region_City_Id: this.actionForm.cityVal[1],
          base_Region_Province_Id: this.actionForm.cityVal[0],
          lon: this.actionForm.lon,
          lat: this.actionForm.lat,
          open_Start_Time: this.actionForm.date
            ? this.actionForm.date[0]
            : "00:00",
          open_End_Time: this.actionForm.date
            ? this.actionForm.date[1]
            : "00:00",
          open_Time: this.actionForm.isDateAll
            ? "24h"
            : this.actionForm.date[0] + "-" + this.actionForm.date[1],
          park: this.actionForm.park,
          scenario: this.actionForm.scenario,
          operations: this.actionForm.operations || 0
        }
      );
      this.$message({
        message: "创建成功！",
        type: "success"
      });
      this.$emit("getData", 1);
      this.resetActionForm();
      this.action.show = false;
    },
    // 修改请求
    async edit() {
      const res = await this.$api.carWashStation.UpdateGetSelfServiceCarWashStationList(
        {
          id: this.actionForm.id,
          station_Name: this.actionForm.station_Name,
          merchant_Num: this.actionForm.merchant_num,
          address: this.actionForm.address,
          base_Region_Id: this.actionForm.cityVal[2],
          base_Region_City_Id: this.actionForm.cityVal[1],
          base_Region_Province_Id: this.actionForm.cityVal[0],
          lon: this.actionForm.lon,
          lat: this.actionForm.lat,
          open_Start_Time:
            (this.actionForm.date && this.actionForm.date[0]) || "00:00",
          open_End_Time:
            (this.actionForm.date && this.actionForm.date[1]) || "00:00",
          open_Time: this.actionForm.isDateAll
            ? "24h"
            : this.actionForm.date[0] + "-" + this.actionForm.date[1],
          park: this.actionForm.park,
          scenario: this.actionForm.scenario,
          operations: this.actionForm.operations || 0
        }
      );
      this.$message({
        message: "修改成功！",
        type: "success"
      });
      this.$emit("getData", 1);
      this.resetActionForm();
      this.action.show = false;
    },
    // 打开添加弹窗
    openAdd() {
      console.log(this.actionForm);
      this.action.type = 1;
      this.action.show = true;
    },
    // 打开修改弹窗
    openEdit(row) {
      this.action.type = 2;
      this.action.show = true;
      this.$nextTick(async () => {
        this.actionForm.address = row.address;
        this.actionForm.id = row.id;
        this.actionForm.station_Name = row.station_Name;
        this.actionForm.merchant_num = row.merchant_Num;
        this.actionForm.lat = row.lat;
        this.actionForm.lon = row.lon;
        this.actionForm.scenario = row.scenario;
        this.actionForm.operations = String(row.operations);
        this.actionForm.park = row.park;
        this.actionForm.cityVal = [
          row.base_Region_Province_Id,
          row.base_Region_City_Id,
          row.base_Region_Id
        ];
        this.actionForm.isDateAll = row.open_Time === "24h" ? true : false;
        if (row.open_Time === "24h") {
          this.actionForm.date = ["00:00", "00:00"];
        } else {
          this.actionForm.date = [
            row.open_Time.split("-")[0],
            row.open_Time.split("-")[1]
          ];
        }
        const res = await this.$api.carWashStation.GetAccountStoreMerchantRelationList(
          {
            merchant_num: row.merchant_Num
          }
        );
        this.baseRegionTable = res.data;
      });
    },
    // 重置操作表单（新增、编辑）
    resetActionForm() {
      this.actionForm.lon = "";
      this.actionForm.lat = "";
      this.actionForm.isDateAll = false;
      this.actionForm.date = null;
      this.baseRegionTable = [];
      this.$refs.actionForm.resetFields();
    },
    // 选择好位置保存经纬度
    submitAddress() {
      this.actionForm.lon = this.mapInfo.lng;
      this.actionForm.lat = this.mapInfo.lat;
      this.mapInfo.show = false;
    },
    // 打开地图获取经纬度
    getLatLon() {
      if (!this.$refs.selectCity.$children[0].getCheckedNodes().length) {
        this.$message.error("请选择站点地址");
        return;
      }
      if (!this.actionForm.address) {
        this.$message.error("请输入详细地址");
        return;
      }
      let address = this.$refs.selectCity.$children[0].getCheckedNodes()[0]
        .pathLabels;
      this.mapInfo.address = address.join("");
      this.mapInfo.address += this.actionForm.address;
      this.mapInfo.show = true;
      console.log(this.mapInfo.address);
    },
    // 提交操作表单（新增、编辑）
    submitActionForm() {
      this.$refs.actionForm.validate(async valid => {
        if (valid) {
          if (!this.actionForm.lon) {
            this.$message.error("请获取经纬度");
            return;
          }
          if (!this.actionForm.date && !this.actionForm.isDateAll) {
            this.$message.error("请选择营业时间");
            return;
          }
          if (this.action.type === 1) {
            this.add();
          } else {
            this.edit();
          }
        } else {
          return false;
        }
      });
    },
    // 验证站点名称是否重复
    async validateStationName(rule, value, callback) {
      if (value) {
        if (this.action.type === 1) {
          const res = await this.$api.carWashStation.GetSelfServiceCarWashStationName(
            {
              station_Name: value
            }
          );
          if (res.data) {
            callback(new Error("站点名称重复，请重新输入"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }
    },
    // 获取所属商户号的所属关系
    async getAccountStoreMerchantRelationList(rule, value, callback) {
      if (value) {
        const res = await this.$api.carWashStation.GetAccountStoreMerchantRelationList(
          {
            merchant_num: value
          }
        );
        this.baseRegionTable = [];
        if (res.data && res.data.length) {
          this.baseRegionTable = res.data;
          callback();
        } else {
          callback(new Error("所属商户号不存在，请重新输入"));
        }
      }
    }
  },
  components: {
    selectCity,
    uploadImg
  }
};
</script>
<style lang="scss" scoped>
.site-address {
  display: flex;
  margin-bottom: 22px;
  margin-left: 100px;
}
.ts {
  color: rgb(255, 149, 2);
  font-size: 12px;
  line-height: 20px;
}

.btn-wrap {
  text-align: center;
}
</style>
